package com.smile.spring;



import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/12/11 17:09
 */
public class MyApplicationContext {
    /**
     * 主配置类
     */
    private Class configClass;

    private Map<String, Object> singletonObjects = new HashMap<>();

    private List<BeanPostProcessor> beanPostProcessorList =new ArrayList<>();

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    public MyApplicationContext(Class configClass) {
        this.configClass = configClass;

        doComponentScan();

        createBean();

    }

    /**
     * 根据扫描后的结果 创建bean
     */
    private void createBean() {
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            //d单例模式，创建bena 享元模式 每次创建
            if (Objects.equals("singleton",beanDefinition.getScope())) {
                Object bean = createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }

    /**
     * 创建bean
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object createBean(String beanName,BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();

            /**
             * bean 属性 填充
             */
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    field.set(instance,getBean(field.getName()));
                }
            }

            /**
             * BeanNameAware setBeanName 回调
             */
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            /**
             *  BeanPostProcessor before 回调
             */
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance,beanName);
            }

            /**
             * InitializingBean  afterPropertiesSet 回调
             */
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }
            /**
             *  BeanPostProcessor after 回调
             */
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 扫描bean
     * 判断 是否 指定bean名称
     * 判断 是否 指定bean模式（单例/享元）
     * 判断 是否 实现 BeanPostProcessor 接口
     *
     */
    private void doComponentScan() {
        String scanPath = "";
        //包含有 ComponentScan 注解
        if (configClass.isAnnotationPresent(ComponentScan.class)) {
            //configClass.getA
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            scanPath = componentScanAnnotation.value();
            // System.out.println("scanPath:"+scanPath);
            scanPath = scanPath.replace(".","/");
            //     com/smile/lyh/service
            ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(scanPath);
            File file = new File(resource.getFile());

            if (file.isDirectory()) {
                for (File listFile : file.listFiles()) {
                    String absolutePath = listFile.getAbsolutePath();
                    //  System.out.println(absolutePath);
///Users/yuhang/devlop/git/tuling-xueyuan-study/tuling-study-parent/tuling-study-spring-all/spring-02/target/classes/com/smile/lyh/service/UserInterface.class
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"),absolutePath.indexOf(".class"));
                    absolutePath = absolutePath.replace("/",".");
                    // com/smile/lyh/service/UserInterface

                    try {
                        Class<?> clazz = classLoader.loadClass(absolutePath);
                        //加载bean
                        if (clazz.isAnnotationPresent(Component.class)) {
                            // 是否实现这个接口？ 后面统一调用方法
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }
                            //是否指定 bean名称，默认 首字母转小写
                            Component componentAnnotation = clazz.getAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            if ("".equals(beanName)) {
                                beanName = Introspector.decapitalize(clazz.getSimpleName());
                            }
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(clazz);
                            //是否设置bean 作用域 默认单例模式
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                String value = scopeAnnotation.value();
                                beanDefinition.setScope(value);
                            } else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public Object getBean(String beanName) {
        if (!beanDefinitionMap.containsKey(beanName)) {
            throw new NullPointerException();
        }

        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);

        if (Objects.equals("singleton",beanDefinition.getScope())) {
            Object singletonBean = singletonObjects.get(beanName);
            if (singletonBean == null) {
                singletonBean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, singletonBean);
            }
            return singletonBean;
        } else {
            // 原型
            Object prototypeBean = createBean(beanName, beanDefinition);
            return prototypeBean;
        }
    }
}
